<template>
  <div class="complaint-submit">
    <div class="sub-page-header">
      <el-tooltip content="点击返回企业判定监测" placement="left">
        <div class="title" @click="goBack">
          <el-button icon="el-icon-arrow-left" type="text"></el-button>
          {{ formDisabled ? '企业判定监测详情' : id ? '修改企业判定监测' : '新增企业判定监测' }}
        </div>
      </el-tooltip>
    </div>
    <el-scrollbar class="apply-box submit-fixed">
      <div class="content">
        <div class="form">
          <el-form
            label-suffix="："
            :model="submitForm"
            :rules="rules"
            label-width="150px"
            ref="dataForm"
            :disabled="formDisabled">
            <div class="section-title syht18">基本信息</div>
            <el-form-item prop="jobName" label="监测规则名称">
              <el-input
                placeholder="请输入"
                v-model="submitForm.jobName"
                maxlength="50"
                show-word-limit
                clearable></el-input>
            </el-form-item>
            <el-form-item label="编码">
              <el-input
                placeholder="请输入"
                v-model="submitForm.jobNum"
                maxlength="20"
                show-word-limit
                clearable></el-input>
            </el-form-item>
            <el-form-item label="关联算法" class="mb0" required>
              <el-form-item
                v-for="(item, index) in submitForm.jobRelInfoDTOList"
                :key="index"
                :prop="`jobRelInfoDTOList.${index}.busId`"
                :rules="rules.busId">
                <el-row>
                  <el-col :span="21" class="rules-select">
                    <el-select
                      v-model="item.busId"
                      placeholder="请选择"
                      filterable
                      popper-class="el-select-wrap"
                      style="width: 100%"
                      clearable
                      @change="onRuleChange">
                      <el-option
                        v-for="item in algorithmList"
                        :key="item.id"
                        :label="item.algorithmName"
                        :value="item.id"
                        :disabled="item.disabled"></el-option>
                    </el-select>
                  </el-col>
                  <el-col :span="3">
                    <i class="plus el-icon-circle-plus" @click="onAddRemove('add', index)"></i>
                    <i
                      class="plus el-icon-remove"
                      v-show="submitForm.jobRelInfoDTOList.length > 1"
                      @click="onAddRemove('remove', index)"></i>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-form-item>
            <el-form-item prop="messageContent" label="监测频率">
              <!-- <cron :value.sync="submitForm.jobCron" :jobCronList="jobCronList"></cron> -->
              <el-select class="full_width" v-model="submitForm.jobCron" clearable>
                <el-option
                  v-for="(item, index) in jobCronList"
                  :key="index"
                  :label="item.name"
                  :value="item.aliasName"></el-option>
              </el-select>
              <!-- <div v-if="jobCronJx.length > 0" class="cornTable">
                <p v-for="(item, index) in jobCronJx" :key="index">{{ index + 1 }}、{{ item }}</p>
              </div> -->
            </el-form-item>
            <el-form-item prop="jobDescribe" label="规则说明">
              <el-input
                placeholder="请输入"
                v-model="submitForm.jobDescribe"
                maxlength="50"
                show-word-limit
                type="textarea"></el-input>
            </el-form-item>
            <el-form-item prop="jobState" label="生效状态">
              <el-radio-group v-model="submitForm.jobState">
                <el-radio v-for="item in stateList" :key="item.key" :label="item.key">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="!formDisabled" class="btns-view">
          <div class="btn-box">
            <el-button class="btn-item" type="primary" @click="submitData">提交</el-button>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script>
import { saveJobApi, editJobApi, getJobDetailApi, listValidAlgorithmApi } from '@api/modules/judgMonitor.js'

import { STATE, RULE_OPER } from '@utility/dict'
// import cron from '@com/cron'
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'judgMonitorCreate',
  components: {
    // cron
  },
  props: {},
  data() {
    return {
      id: '',
      jobCronJx: [],
      stateList: STATE._keys.map(key => {
        return {
          key,
          label: STATE._label[key],
        }
      }),
      ruleOperList: RULE_OPER._keys.map(key => {
        return {
          key,
          label: RULE_OPER._label[key],
        }
      }),
      algorithmListAll: [],
      algorithmList: [],
      submitForm: {
        jobType: '',
        jobNum: '',
        jobName: '',
        jobDescribe: '',
        jobCron: '',
        jobState: '1',
        jobRelInfoDTOList: [
          {
            busId: '',
            busType: 'ALGORITHM',
            remark: '',
          },
        ],
      },
      rules: {
        jobName: [{ required: true, message: '请输入监测任务名称', trigger: 'blur' }],
        jobState: [{ required: true, message: '请选择生效状态', trigger: 'blur' }],
        busId: [{ required: true, message: '请选择关联算法', trigger: 'change' }],
      },
    }
  },
  computed: {
    ...mapGetters('publicCode', ['getCode']),
    formDisabled() {
      return this.$route.params.view
    },
  },
  watch: {
    'formData.jobCron': function (a, b) {
      if (b) {
        this.initCornTimes()
      }
    },
  },
  created() {
    this.getListAllRulesData()
    this.getDictData()
    const { id } = this.$route.params
    this.id = id
    if (this.id) {
      this.getDetailData()
    }
  },
  mounted() {},
  methods: {
    ...mapActions('publicCode', ['getListDictData']),
    getDetailData() {
      getJobDetailApi({ id: this.id }).then(res => {
        if (res.code === 0) {
          this.onRuleChange()
          this.submitForm = { ...this.submitForm, ...res.data }
          this.submitForm.jobState = String(this.submitForm.jobState)
          this.submitForm.jobRelInfoDTOList = [...this.submitForm.jobRelInfoVOList]
        }
      })
    },
    // 获取政策列表
    getListAllRulesData() {
      listValidAlgorithmApi({ effectiveStatus: 1 }).then(res => {
        if (res.code === 0) {
          this.algorithmListAll = res.data
          if (!this.id) {
            this.algorithmList = res.data
          }
        }
      })
    },
    // 监听规则切换
    onRuleChange() {
      const ruleIds = this.submitForm.jobRelInfoDTOList.map(item => item.busId)
      if (this.algorithmListAll.length) {
        this.algorithmListAll.forEach(item => {
          if (ruleIds.includes(item.id)) {
            item.disabled = true
          } else {
            item.disabled = false
          }
        })
      }
      const listJson = JSON.stringify(this.algorithmListAll)
      this.algorithmList = JSON.parse(listJson)
    },
    submitData() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          const params = { ...this.submitForm }

          let API = null
          if (params.id) {
            API = editJobApi
          } else {
            API = saveJobApi
          }
          API(params).then(res => {
            if (res.code === 0) {
              this.$message.success('操作成功')
              this.goBack()
            }
          })
        }
      })
    },
    initCornTimes() {
      const arrays = this.formData.jobCron.split(' ')
      if (arrays[3] === '?' && arrays[5] === '?') {
        this.$message.error('日期与星期不可以同时为“不指定”')
        this.jobCronJx = []
        return
      }
      if (arrays[3] !== '?' && arrays[5] !== '?') {
        this.$message.error('日期与星期必须有一个为“不指定”')
        this.jobCronJx = []
        return
      }
      this.jobCronJx = []
      // listAfterAFewTimes({
      //   jobCron: this.formData.jobCron,
      //   times: this.times,
      // }).then(res => {
      //   this.jobCronJx = res.data ? res.data : []
      // })
    },
    async getDictData() {
      // 获取内置cron表达式
      await this.getListDictData({ param: 'JOB_CRON' })

      const { JOB_CRON } = this.getCode
      this.jobCronList = [...JOB_CRON]
    },
    // 添加移除规则
    onAddRemove(type, index) {
      if (type === 'add') {
        this.submitForm.jobRelInfoDTOList.splice(index + 1, 0, {
          busId: '',
          busType: 'ALGORITHM',
        })
      } else {
        this.submitForm.jobRelInfoDTOList.splice(index, 1)
      }
      this.onRuleChange()
    },
    goBack() {
      this.$router.back(-1)
    },
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onWindowResize)
  },
}
</script>

<style lang="scss" scoped>
.complaint-submit {
  height: 100%;
  @include flex-y;
  position: relative;
  background: #f5f6fa;
  padding: 20px;
  .el-scrollbar {
    @include flex-1;
  }
  ::v-deep .el-select-group {
    display: flex;
    flex-wrap: wrap;
  }

  .apply-box {
    background-color: #fff;
    .content {
      padding: 20px 30px;
      width: 75%;
    }
    .plus {
      cursor: pointer;
      font-size: 22px;
      margin-left: 10px;
    }
    .rules-select {
      display: flex;
    }
    .rule-oper {
      margin-right: 10px;
    }
    .section-title {
      padding: 10px;
      background: #f0f4f9;
      margin-bottom: 15px;
    }
    ::v-deep .form {
      .el-form-item {
        margin-bottom: 24px;
      }
    }
  }
  .btns-view {
    // @include flex-x(center, center);
    text-align: center;
    // border-top: 1px solid $-border-color-base;
    margin-top: 10px;
    padding: 20px;
    background-color: #fff;
    .other-btn-box {
      margin-top: 10px;
      text-align: center;
    }
    .btn-item {
      width: 120px;
      height: 40px;
      font-size: 16px;
    }
    .empty {
      background-color: transparent;
      color: #4a79ba;
    }
  }
  .submit-fixed {
    padding-bottom: 100px;
    .btns-view {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
    }
  }

  @media screen and(max-width:800px) {
    .apply-box {
      .content {
        padding: 20px;
      }
    }
    .msg-container {
      .section-title {
        padding: 20px 50px;
        font-size: 36px;
        .icon-img-ts,
        .icon-img-person {
          display: inline-block;
          height: 36px;
          vertical-align: middle;
          margin-right: 10px;
          margin-top: -5px;
        }
      }
    }
    .el-input__count {
      font-size: 24px;
    }
  }
}
</style>
